package com.qxzn.app.personalcenter.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.ContactsBean;
import com.qxzn.app.bean.FaceDetectionBean;
import com.qxzn.app.bean.FaceIdListBean;
import com.qxzn.app.bean.FaceIdPrivilegeBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.util.GlideImageLoader;
import com.qxzn.app.page.view.CustomItemView;
import com.qxzn.app.personalcenter.R;
import com.qxzn.app.personalcenter.R2;
import com.qxzn.app.personalcenter.adapter.ContactsAdapter;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.DisplayUtil;
import com.qxzn.app.util.FileUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import news.jaywei.com.compresslib.CompressTools;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 上传人脸信息、修改人脸信息
 */
public class UploadFaceIDActivity extends BaseActivity {
    @BindView(R2.id.ll_root)
    LinearLayout llRoot;
    @BindView(R2.id.civ_head)
    CustomItemView civHead;
    @BindView(R2.id.civ_nickname)
    CustomItemView civNickname;
    @BindView(R2.id.civ_bind_user)
    CustomItemView civBindUser;
    @BindView(R2.id.civ_privilege)
    CustomItemView civPrivilege;
    @BindView(R2.id.tv_bind)
    TextView tvBind;
    private List<String> mSelected;
    private String faceIdPath;
    private ImageView ivHead;
    private List<FaceIdPrivilegeBean> privilegeList = new ArrayList<>();
    private List<ContactsBean.DataBean> contactsList = new ArrayList<>();

    private OptionsPickerView<String> privilegeOptions;
    private OptionsPickerView<String> bindUserOptions;
    private int bindPosition;
    private String faceId, faceUrl, nickName, bindUserId, bindUserName, privilegeId;
    private RxPermissions rxPermissions;
    private FaceIdListBean.DataBean dataBean;

    @Override
    protected int initLayout() {
        return R.layout.activity_upload_faceid;
    }

    @Override
    protected void initView() {
        ivHead = civHead.getIvRightIcon();
        ivHead.setOnClickListener(this);
//        llRoot.getViewTreeObserver().addOnGlobalLayoutListener(() -> setStatusBar());
    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("上传人脸信息");
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        dataBean = (FaceIdListBean.DataBean) getIntent().getSerializableExtra("data");
        if (dataBean != null) {
            faceId = dataBean.getId() + "";
            faceUrl = HttpRequest.BASE_URL + dataBean.getFile();
            nickName = dataBean.getNiname();
            bindUserName = dataBean.getNiname();// TODO: 2019/5/23
            bindUserId = dataBean.getUsername();
            privilegeId = dataBean.getRoles() + "";

            Glide.with(this).load(faceUrl).apply(new RequestOptions().placeholder(R.mipmap.logo).error(R.mipmap.logo)).into(civHead.getIvRightIcon());
            civNickname.setRightEditText(nickName);
            civBindUser.setRightText(bindUserName);
            if ("1".equals(privilegeId)) {
                civPrivilege.setRightText("访问数据权限");
            } else {
                civPrivilege.setRightText("语音播报权限");
            }

            if (!TextUtils.isEmpty(bindUserId)) {
                iv_right.setVisibility(View.VISIBLE);
                iv_right.setImageResource(R.mipmap.logo);
                iv_right.setOnClickListener(this);
            }

            tv_title.setText("修改人脸信息");
        } else {
            tv_title.setText("新增人脸信息");
        }

        rxPermissions = new RxPermissions(this);

        FaceIdPrivilegeBean bean = new FaceIdPrivilegeBean();
        bean.setId("2");
        bean.setName("语音播报权限");
        privilegeList.add(bean);

        FaceIdPrivilegeBean bean1 = new FaceIdPrivilegeBean();
        bean1.setId("1");
        bean1.setName("访问数据权限");
        privilegeList.add(bean1);

//        ContactsBean.DataBean bean4 = new ContactsBean.DataBean();
//        bean4.setMemName("");
//        bean4.setMemRemarks("非家庭成员用户");
//        contactsList.add(bean4);

        ContactsBean.DataBean bean3 = new ContactsBean.DataBean();
        bean3.setMemName(SharePreferenceUtil.getUserName(this));
        bean3.setMemRemarks("我");
        contactsList.add(bean3);

        getContacts();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.iv_right_icon) {
        } else if (view.getId() == R.id.iv_right) {
            showDialog("删除人脸", "是否确认删除该人脸", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    showProgress();
                    deleteFaceId();
                }
            });
        }
    }

    @OnClick({R2.id.civ_head, R2.id.tv_bind, R2.id.civ_bind_user, R2.id.civ_privilege})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.civ_head) {
            getPermission();
        } else if (i == R.id.tv_bind) {//上传人脸信息
            submit();
        } else if (i == R.id.civ_bind_user) {
            showBindPicker();
        } else if (i == R.id.civ_privilege) {
            showPrivilegePicker();
        }
    }

    private void submit() {
        nickName = civNickname.getRightEditText();
        if (TextUtils.isEmpty(nickName)) {
            AppUtil.showToast(this, "请输入该用户的昵称");
            return;
        }
        if (TextUtils.isEmpty(bindUserId)) {
            AppUtil.showToast(this, "请选择该人脸需要关联的用户");
            return;
        }
        if (TextUtils.isEmpty(privilegeId)) {
            AppUtil.showToast(this, "请选择该人脸可拥有的权限");
            return;
        }
        if (TextUtils.isEmpty(faceId)) {//上传人脸
            if (TextUtils.isEmpty(faceIdPath)) {
                AppUtil.showToast(this, "请选择需要上传的人脸照片");
                return;
            }
            showProgress();
            compressImg(false);
        } else {//修改人脸信息
            showProgress();
            modifyFaceInfo();
        }
    }

    private void showBindPicker() {
        if (bindUserOptions == null) {
            bindUserOptions = new OptionsPickerBuilder(UploadFaceIDActivity.this, null).setLayoutRes(R.layout.picker_contacts, v -> {
                AppUtil.showLog("layout初始化");
                ViewHolder holder = new ViewHolder(v);
                holder.lrvContacts.setLayoutManager(new LinearLayoutManager(this));
                ContactsAdapter adapter = new ContactsAdapter(this, contactsList);
                adapter.setItemClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bindPosition = (int) v.getTag();
                        bindUserId = contactsList.get(bindPosition).getMemName();
                        String remark = contactsList.get(bindPosition).getMemRemarks();
                        if (!TextUtils.isEmpty(remark)) {
                            if (bindPosition != 0) {
                                remark = "(" + remark + ")";
                            }
                        } else {
                            remark = "";
                        }
                        civBindUser.setRightText(contactsList.get(bindPosition).getMemName() + remark);
                        bindUserOptions.dismiss();
                        AppUtil.showLog("点击位置：" + bindPosition);
                    }
                });
                holder.lrvContacts.setAdapter(adapter);
            }).build();
        }
        bindUserOptions.show();
    }

    private void showPrivilegePicker() {
        if (privilegeOptions == null) {
            privilegeOptions = new OptionsPickerBuilder(UploadFaceIDActivity.this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    privilegeId = privilegeList.get(options1).getId();
                    String tx = privilegeList.get(options1).getName();
                    civPrivilege.setRightText(tx);
                    AppUtil.showLog(tx);
                }
            }).setTitleText("请选择该人脸的权限").setSubmitColor(getResources().getColor(R.color.white)).setCancelColor(getResources().getColor(R.color.main_blue))
                    .setTitleBgColor(getResources().getColor(R.color.main_blue)).setTitleColor(getResources().getColor(R.color.white)).build();
            List<String> items = new ArrayList<>();
            for (FaceIdPrivilegeBean bean : privilegeList) {
                items.add(bean.getName());
            }
            privilegeOptions.setPicker(items);
        }
        privilegeOptions.show();
    }

    private void getPermission() {
        rxPermissions.requestEachCombined(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(permission -> {
                    if (permission.granted) {
                        getPicture(1, 0);
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        showPermissionDialog("该功能需要存储权限和相机权限", (dialog, which) -> {
                            getPermission();
                        });
                    } else {
                        showPermissionDialog("该功能需要存储权限和相机权限");
                    }
                });
    }

    private void getPicture(int maxSelectable, int requestCode) {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .capture(true)
                .maxSelectable(maxSelectable)
                .captureStrategy(new CaptureStrategy(true, Constant.authority))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideImageLoader.Glide4Engine())
                .forResult(requestCode);
    }

    private void compressImg(boolean isModify) {
        File file = new File(faceIdPath);
        AppUtil.showLog(file.exists() + "：路径：" + file);
        CompressTools tool = new CompressTools.Builder(this).setDestinationDirectoryPath(FileUtil.getBaseImagePath(this)).build();
        tool.compressToFileJni(file, new CompressTools.OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                AppUtil.showLog(file.exists() + "压缩成功：" + file);
                if (isModify) {
                    searchFaceId(file);
//                    modifyFaceID(file);
                } else {
                    uploadFaceID(file);
                }
            }
        });
    }

    private void uploadFaceID(File file) {
        MultipartBody.Part fileBody = HttpRequest.getPartFileBody(file);
        RequestBody device_id = HttpRequest.getPartBody(SharePreferenceUtil.getDeviceId(this));
        RequestBody username = HttpRequest.getPartBody(bindUserId);
        RequestBody roles = HttpRequest.getPartBody(privilegeId);
        RequestBody nickname = HttpRequest.getPartBody(nickName);
        Call<BaseBean> call = HttpRequest.getService().uploadFaceID(device_id, username, roles, nickname, fileBody);
        callBack(call, "人脸信息上传");
    }

    private void modifyFaceID(File file) {
        MultipartBody.Part fileBody = HttpRequest.getPartFileBody(file);
        RequestBody device_id = HttpRequest.getPartBody(SharePreferenceUtil.getDeviceId(this));
        RequestBody username = HttpRequest.getPartBody(bindUserId);
        RequestBody id = HttpRequest.getPartBody(faceId);
        Call<BaseBean> call = HttpRequest.getService().modifyFaceID(device_id, username, id, fileBody);
        callBack(call, "人脸照片修改");

//        new Thread(new Runnable() {// TODO: 2019/9/3
//            @Override
//            public void run() {
//                try {
//                    String a = Base64Util.encode(com.qxzn.app.page.util.face.FileUtil.readFileByBytes(file.getAbsolutePath()));
//                    String result = FaceUtil.search("BASE64", a, "9ac019acab486ad7db721f2b6f1b94a8", "13266762855");
//                    AppUtil.showLog(result);
//                } catch (IOException e) {
//                    AppUtil.showLog("异常：" + e);
//                    e.printStackTrace();
//                }
//            }
//        }).start();
    }

    private void modifyFaceInfo() {
        JSONObject params = new JSONObject();
        params.put("device_id", SharePreferenceUtil.getDeviceId(this));
        params.put("username", bindUserId);
        params.put("roles", privilegeId);
        params.put("niname", nickName);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), JSON.toJSON(params) + "");
        Call<BaseBean> call = HttpRequest.getService().modifyFaceInfo(body);
        callBack(call, "人脸信息修改");
    }

    private void deleteFaceId() {
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), "{\"device_id\":\"" + SharePreferenceUtil.getDeviceId(this) + "\",\"username\":\"" + bindUserId + "\"}");
        Call<BaseBean> call = HttpRequest.getService().deleteFaceId(body);
        callBack(call, "人脸信息删除");
    }

    private void searchFaceId(File file) {
        RequestBody device_id = HttpRequest.getPartBody("9ac019acab486ad7db721f2b6f1b94a8");
//        RequestBody device_id = HttpRequest.getPartBody(SharePreferenceUtil.getDeviceId(this));
        MultipartBody.Part fileBody = HttpRequest.getPartFileBody(file);
        Call<BaseBean<FaceDetectionBean>> call = HttpRequest.getService().faceDetection(/*device_id, */fileBody);
//        callBack(call, "人脸验证");
    }

    private void callBack(Call<BaseBean> call, String noticeInfo) {
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                AppUtil.showLog("回调：" + response.body().toString());
                hideProgress();
                BaseBean baseBean = response.body();
                if (baseBean != null) {
                    if (baseBean.getCode() == 200) {
                        if (TextUtils.isEmpty(baseBean.getMsg())) {
                            AppUtil.showToast(UploadFaceIDActivity.this, noticeInfo + "成功");
                        } else {
                            AppUtil.showToast(UploadFaceIDActivity.this, baseBean.getMsg());
                        }
                        setResult(RESULT_OK);
                        finish();
                        return;
                    } else {
                        if (!TextUtils.isEmpty(baseBean.getMsg())) {
                            AppUtil.showToast(UploadFaceIDActivity.this, baseBean.getMsg());
                            return;
                        }
                    }
                }
                AppUtil.showToast(UploadFaceIDActivity.this, noticeInfo + "失败");
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                AppUtil.showToast(UploadFaceIDActivity.this, "网络有点问题，" + noticeInfo + "失败");
                t.printStackTrace();
            }
        });
    }

    private void getContacts() {
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), "{\"device_id\":\"" + SharePreferenceUtil.getDeviceId(this) + "\",\"username\":\"" + SharePreferenceUtil.getUserName(this) + "\"}");
        Call<ContactsBean> call = HttpRequest.getService().getContacts(body);
        call.enqueue(new Callback<ContactsBean>() {
            @Override
            public void onResponse(Call<ContactsBean> call, Response<ContactsBean> response) {
                ContactsBean keyBean = response.body();
                if (keyBean != null) {
                    if (keyBean.getCode() == 200) {
                        List<ContactsBean.DataBean> userList = keyBean.getData();
                        if (userList != null) {
                            contactsList.addAll(userList);
                        }
                        return;
                    }
                }
                if (keyBean != null && !TextUtils.isEmpty(keyBean.getMsg())) {
                    AppUtil.showToast(UploadFaceIDActivity.this, keyBean.getMsg());
                } else {
                    AppUtil.showToast(UploadFaceIDActivity.this, "网络错误，请稍后再试！");
                }
            }

            @Override
            public void onFailure(Call<ContactsBean> call, Throwable t) {
                AppUtil.showToast(UploadFaceIDActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainPathResult(data);
            AppUtil.showLog("mSelected: " + mSelected + "\n");
            if (mSelected != null && mSelected.size() > 0) {
                faceIdPath = mSelected.get(0);
                Glide.with(this).load(faceIdPath).apply(new RequestOptions().override(DisplayUtil.dip2px(this, 80))).into(ivHead);
//                if (!TextUtils.isEmpty(faceId)) {
                compressImg(true);
//                }
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();
            if (AppUtil.isShouldHideInput(v, ev)) {
                AppUtil.hideSoftInput(this, v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    static class ViewHolder {
        @BindView(R2.id.tv_title)
        TextView tvTitle;
        @BindView(R2.id.tv_cancel)
        TextView tvCancel;
        @BindView(R2.id.tv_confirm)
        TextView tvConfirm;
        @BindView(R2.id.lrv_contacts)
        RecyclerView lrvContacts;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
